package com.example.lin.qrcodescanning;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.activity.CaptureActivity;
import com.google.zxing.encoding.EncodingHandler;
import com.utils.CommonUtil;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {


    private Button btn_scan;
    private Button btn_createCode;
    private TextView tv_show;
    private EditText et_code;
    private ImageView iv_code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn_scan = findViewById(R.id.btn_scan);
        btn_createCode = findViewById(R.id.btn_createCode);
        btn_scan.setOnClickListener(this);
        btn_createCode.setOnClickListener(this);
        tv_show = findViewById(R.id.tv_show);
        et_code = findViewById(R.id.et_code);
        iv_code = findViewById(R.id.iv_code);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将动态权限的回调 交由 EasyPermissions 处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 摄像头权限申请的请求码
     */
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 321;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
                if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
                    goQrCodeScan();
                } else {
                    //未获得 摄像头 权限,则申请
                    PermissionRequest build = new PermissionRequest.Builder(this, CAMERA_PERMISSION_REQUEST_CODE, Manifest.permission.CAMERA)
                            .setRationale("二维码扫描需要用到摄像头权限!")
                            .setPositiveButtonText("好的")
                            .setNegativeButtonText("不扫描了").build();
                    EasyPermissions.requestPermissions(build);
                }
                break;
            case R.id.btn_createCode:
                try {
                    String s = et_code.getText().toString();
                    //生成二维码(参数一:字符串,参数二:二维码图片的大小/px)
//                    Bitmap qrCode = EncodingHandler.createQRCode(s, 400);
                    //生成二维码(参数一:字符串,参数二:二维码图片的大小/px)
                    Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.img12);
                    Bitmap qrCode = EncodingHandler.createQRCode(s, 400, 400, logo);
                    iv_code.setImageBitmap(qrCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 从 MainActivity 跳转到 CaptureActivity 的请求码
     */
    private static final int MAIN_TO_CAPTURE_REQUEST_CODE = 1001;

    private void goQrCodeScan() {
        if (CommonUtil.isCameraCanUse()) {
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, MAIN_TO_CAPTURE_REQUEST_CODE);
        } else {
            Toast.makeText(this, "摄像头已损坏,或权限没有获取", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i("ABC", "onActivityResult: " + requestCode + "," + resultCode + "," + data);
        if (resultCode == CaptureActivity.RESULT_CODE_QR_SCAN && requestCode == MAIN_TO_CAPTURE_REQUEST_CODE) {
            if (data != null) {
                String result = data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN);
                if (result.startsWith("friend")) {
                    String friendNumber = result.substring(result.indexOf(":") + 1);
                    Toast.makeText(this, "添加好友:" + friendNumber, Toast.LENGTH_SHORT).show();
                } else if (result.startsWith("pay")) {
                    String k = result.substring(result.indexOf(":") + 1);
                    String[] split = k.split("=");
                    String friendNum = split[0];
                    double price = Double.parseDouble(split[1]);
                    Toast.makeText(this, "付款:" + friendNum + "   金额:" + price, Toast.LENGTH_SHORT).show();
                } else if (result.startsWith("http")) {
                    Uri uri = Uri.parse(result);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } else {
                    tv_show.setText(result);
                }
            }

        }


    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE && perms.get(0).equals(Manifest.permission.CAMERA)) {
            goQrCodeScan();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "未获得摄像头权限!", Toast.LENGTH_SHORT).show();
    }
}
